<template>
  <!--文档管理上传文件弹框-->
  <el-dialog
    title="上传文件"
    :visible.sync="dialogVisible"
    width="600px"
    customClass="mes_dialog"
    v-dialogDrag
    :close-on-click-modal="false">
    <div class="mes_file_secret" v-if="dialogVisible">
      <div class="import_item">
        <div class="import_label">
          <span class="import_required">*</span>文档密级：
        </div>
        <div class=" import_cont">
          <el-select v-model="secrecyGrade" size="small" placeholder="请选择密级">
            <el-option
              v-for="item in fileSecretLevel"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="import_item" v-if="fileType">
        <div class="import_label">
          <span class="import_required">*</span>文档类型：
        </div>
        <div class=" import_cont">
          <el-select v-model="fileTypeId" size="small" placeholder="请选择类型">
            <el-option
              v-for="(item, index) in FileTypeList"
              :key="index"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="import_item">
        <div class="import_label"><span class="import_required">*</span>选择文件：</div>
        <div class="import_cont">
          <el-upload
            ref="upload"
            class="file_list_cont"
            action=""
            :accept="acceptFiles.toString()"
            multiple
            :auto-upload="false"
            :http-request="handleAdd"
            :on-change="handleChange"
            :on-remove="removeFile"
            list-type="scroll"
            :file-list="fileList">
            <div class="mes_btn">
              <el-button size="small" class="file_btn">
                <i class="iconfont icon-btn_addnew" style="color:#00b4ff;"></i>
                选择文件
              </el-button>
              <span class="accept_text" @click.stop="">支持{{acceptFiles.join('、')}}格式</span>
            </div>
          </el-upload>
        </div>
      </div>
    </div>
    <span slot="footer" class="mes_btn">
      <el-button
        @click="handleUpload"
        type="primary">确定
      </el-button>
      <el-button
        @click="handleCancel"
      >取消
      </el-button>
    </span>
  </el-dialog>
</template>

<script>

export default {
  name: 'SecretUploadDialog',
  props: {
    moduleName: {
      type: String,
      required: true
    },
    module: {
      type: String,
      required: true
    },
    saveInterFace: {
      type: String,
      required: true
    },
    fileType: {
      type: String,
      default: ''
    },
    acceptFiles: {
      type: Array,
      default() {
        return ['.doc', '.docx', '.xls', '.xlsx', '.pdf', '.cxp']
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      fileList: [], // 所选文件列表
      secrecyGrade: '', // 密级
      fileTypeId: '', // 文档类型
    }
  },
  computed: {
    // 文档类型
    FileTypeList() {
      return this.$store.state.dict.FileType.labels || []
    },
    fileSecretLevel() {
      return this.$store.state.dict.fileSecretLevel.labels || []
    }
  },
  methods: {
    openDialog() {
      this.secrecyGrade = this.defaultFileLevel
      this.fileTypeId = ''
      this.fileList = []
      this.dialogVisible = true
    },
    handleCancel() {
      this.dialogVisible = false
    },
    handleUpload() {
      if (!this.secrecyGrade) {
        return this.$message({
          type: 'error',
          message: '请先选择文档密级',
          duration: 1500,
          center: true
        })
      } else if (this.fileType && !this.fileTypeId) {
        return this.$message({
          type: 'error',
          message: '请先选择文档类型',
          duration: 1500,
          center: true
        })
      } else if (!this.fileList.length) {
        return this.$message({
          type: 'error',
          message: `请先选择后缀为${this.acceptFiles.join('、')}的文件`,
          duration: 1500,
          center: true
        })
      }
      this.dialogVisible = false
      this.$refs.upload.submit()
    },
    handleChange(file, fileList) {
      if (this.acceptFiles.some(type => file.name.endsWith(type))) {
        this.fileList.push(file)
      } else if (!this.acceptFiles.length) {
        this.fileList.push(file)
      } else {
        fileList.pop()
      }
    },
    removeFile(file, fileList) {
      this.fileList = fileList
    },
    handleAdd(content) {
      let file = content.file
      let uid = new Date().getTime()
      let source = this.$axios.CancelToken.source()
      let fileItem = {
        status: 'uploading',
        name: file.name,
        size: file.size,
        percentage: 0,
        uid: uid,
        raw: file,
        module: this.module,
        moduleName: this.moduleName,
        source: source
      }
      this.$store.commit('SetModuleState', {moduleState: 2})
      this.$store.commit('AddFileItem', fileItem)
      this.uploadFile(content.file, uid, source.token)
    },
    // 上传文件
    uploadFile(file, uid, cancelToken) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('fileSecretLevelId', this.secrecyGrade)
      this.$store.dispatch('importFileSave', {
        data: formData,
        cancelToken,
        onUploadProgress: (event) => this.$store.commit('UpdateFileListPercentage', {event, uid})
      }).then(res => {
        if (res.id) {
          return this.writeHistory(res.id)
        }
      }).then(() => {
        this.$store.commit('SetFileStatus', {uid: uid, status: 'success'})
      }).catch(err => {
        if (this.$axios.isCancel(err)) {
          this.$store.commit('SetFileStatus', {uid: uid, status: 'cancel'})
        } else {
          this.$store.commit('SetFileStatus', {uid: uid, status: 'failed'})
        }
      })
    },
    // 写入记录
    writeHistory(id) {
      let postData = {
        method: 'post',
        url: this.saveInterFace,
        data: {
          uploadHistoryId: id,
          viewSource: 100
        },
        noCommit: true
      }
      if (this.fileTypeId && this.fileType) postData.data[this.fileType] = this.fileTypeId
      return this.$store.dispatch('saveData', postData).then(() => {
        this.$emit('uploadComplete')
      })
    },
  }
}
</script>

<style lang="less">
  .el-upload-list--scroll {
    max-height: 260px;
    overflow-y: auto;
  }
</style>
